#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<string.h>
#include<stdio.h>

#define commanline 1024
#define lable "$"
char pwd[commanline];
char myenv[commanline];
int argc =0;
void getpwd()
{
	getcwd(pwd,sizeof(pwd)-1);
}
int lastcode = 0;
extern char** envrion ;
char  comman[commanline];
char*  argv[commanline];
char*  env[commanline];
void interact(char * cline,int size)
{
	getpwd();
	//interact
	printf("[%s@%s:%s]",getenv("USER"),getenv("HOSTNAME"),pwd);
	fgets(cline,size,stdin);//通过fgets得到输入
	//abcd\n\0
    comman[strlen(cline)-1] = '\0';//消除输入的换行符
//	printf("%s",cline);
}
int splitcomman(char * cline)
{

	int i = 0;
	char * str = strtok(cline," ");//将命令字符串切割并存入argv中
//	printf("%s",str);
int argc = 0;
    while(str!=NULL)
	{
	argv[i] = str;
	str = strtok(NULL," ");
	argc++;
	i++;
	
	if(argc==0)
	{
		continue;
	}
	}
	argv[i] = NULL;//需要将最后一个字符变为NULL
	return argc;
//	i = 0;
//	while(argv[i])
//	{
//	printf("%d:%s ",i,argv[i]);
//	i++;
	}

void execute()
{
	int i = 0;
	pid_t id = fork();
	if(id ==0)
	{
      execvp(argv[0],argv);
	
			exit(1);
	}
	if(id>0)
	{
		int status = 0;
		pid_t rid = waitpid(id, &status, 0);
		if(rid ==id)
		{

		 lastcode = WEXITSTATUS(status);
		}
	}
	if(id<0)
	{
	perror("fork");
	exit(2);
	}
	//if(argc)

}
int buildcomman()
{
 if(argc==2&&strcmp(argv[0],"cd")==0)
{
	chdir(argv[1]);
	getpwd();
	sprintf(getenv("PWD"),"%s",pwd);//将PWD用pwd进行格式化输入
//	if(strcmp(argv[1],"..")==0)
//	{
//			return;
//	}
//	else if(strcmp(argv[1],".")==0)
//	{
//		return;
//	}
//	else 
//	{
//		getpwd();
//		sprintf(getenv("PWD"),"PWD=%s",pwd);
//		//putenv(argv[1]);
//	}
		return 1;
	}
	 if(strcmp(argv[0],"ls")==0)
	 {
		 argv[argc++] = "--color";
		 argv[argc]=="\0";
	 }
  if(argc==2&&strcmp(argv[0],"export")==0)
{
	strcpy(myenv,argv[1]);
	putenv(myenv);
	return 1;
}
 if(argc==2&&strcmp(argv[0],"echo")==0)
 {
	 if(strcmp(argv[1],"$?")==0)
	 {
		 printf("%d\n",lastcode);
		 lastcode = 0;
	 }
	 else if(*argv[1]=='$')
	 {
		 char*  val = getenv(argv[1]+1);
		 if(val)
	 printf("%s\n",val);
	 }
	 else
		 printf("%s\n",argv[1]);
	 return 1;
 }
 return 0;
}
int main()
{
	int quit = 0;
	while(!quit)
	{
	interact(comman,sizeof(comman));
	argc = splitcomman(comman);
	int i = buildcomman();
//	printf("%d",argc);
	// continue;
   //普通命令
  if(i==0)execute();
  }
//	printf("%s",getenv("HOSTNAME"));
	return 0;
}
